package cn.johnyu.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SecurityException;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    private static final   String  secretKeyValue="abcdefghijklmnopqrstuvwxyz123456";//密钥值必须大于等于32
    private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(secretKeyValue.getBytes());//生成加密钥对象
    //另外一种生成密钥的方式
    private static final SecretKey SECRET_KEY1 = Keys.secretKeyFor(SignatureAlgorithm.HS256);
   private static final Date expireDate=new Date(System.currentTimeMillis()+1000*600);//过期时间一分钟
    public static String generateToken(String subject) {
        return Jwts.builder()
                .signWith(SECRET_KEY)
                .setExpiration(expireDate)
                .setSubject(subject).compact();
    }

    public static String fromToken(String token) {

        Claims claims = null;
        try {
            claims=(Claims) Jwts.parser()
                    .setSigningKey(SECRET_KEY) // 设置签名密钥
                    .build().parse(token).getBody();
        } catch (RuntimeException e) {
            return null;
        }
        return  claims.getSubject();

    }

    public static void main(String[] args) {
        String token = generateToken("这是加密的信息，可以是json字符串");
        System.out.println(token);
        System.out.println(fromToken(token));
    }
}
